package crod

import (
	"context"
	"errors"
	"time"

	"gitee.com/jieyang/go/clog"
	"gitee.com/jieyang/go/utils"
	"github.com/go-rod/rod"
	"github.com/go-rod/rod/lib/launcher"
)

var browser *rod.Browser

func Init() {
	headless := utils.EnvGet("rod", "headless").MustBool(true)
	path, _ := launcher.LookPath()
	// RodPool = rod.NewPagePool(5)
	u := launcher.New().Bin(path).Headless(headless).MustLaunch()
	browser = rod.New().ControlURL(u).MustConnect()
}

// 默认
func GetUrl(url string) []byte {
	return GetPage(url, "html", 20*time.Second)
}

func GetPage(url string, ele string, d time.Duration) []byte {
	clog.Debug().Msg(url)
	if browser == nil {
		Init()
	}
	var page *rod.Page
	err := rod.Try(func() {
		page = browser.Timeout(d).MustPage()
	})
	if err != nil {
		clog.Info().Msg(err.Error())
		return []byte(``)
	}
	defer page.Close()
	var pageelm *rod.Element
	err = rod.Try(func() {
		pageelm = page.Timeout(d).MustNavigate(url).MustElement(ele)
	})
	if errors.Is(err, context.DeadlineExceeded) {
		clog.Debug().Msg("超时错误")
		return []byte(``)
	} else if err != nil {
		clog.Debug().Msg("其他错误")
		return []byte(``)
	}
	body := pageelm.MustHTML()
	//clog.Debug().Msg(body)
	return []byte(body)
}
